import apiMod from "@/apiMod";
import * as turf from "@turf/turf";
import nanjingJson from "@/components/AplidCharts/data/nanjing_outline.json";

export const getAssetsFile = (url: string) => {
  return new URL(`../assets/imgs/${url}`, import.meta.url).href;
};

/**
 * obs 图片预览
 * @param path
 * @returns
 */
export const DowloadPreviewImage = (path: string, type?: string) => {
  return new Promise((resolve, reject) => {
    if (!path) {
      resolve(path);
      return;
    }
    const fileName = path
      .replace(
        "https://obs-mzj-nxylzh.obsv3.nj-ql-1.njql.gov.cn:443/ningxiang%2F",
        ""
      )
      .replace(
        "https://aplid-51.oss-cn-hangzhou.aliyuncs.com:443/ningxiang%2F",
        ""
      )
      .replace(
        "https://apld-51.obs.cn-north-4.myhuaweicloud.com:443/ningxiang%2F",
        ""
      )
      .replace(
        "https://aplid-51.oss-cn-hangzhou.aliyuncs.com:443/ningxiang/",
        ""
      );
    apiMod
      .previewFileDowload(fileName)
      .then((blob) => {
        let url = window.URL.createObjectURL(blob);
        if (type == "blob") {
          resolve(blob);
        } else {
          resolve(url);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

/**
 * jsonp 消息发送
 * @param {*} url
 * @param {*} data
 * @param {*} method
 * @returns
 */
export const ajaxJsonp = ({ url, data, method = "get" }) => {
  return new Promise((resolve, reject) => {
    // 异步对象
    let ajax = new XMLHttpRequest();
    // get 跟post  需要分别写不同的代码
    if (method == "get") {
      let ret = "";
      // get请求
      if (data) {
        if (typeof data === "string") {
          ret = "&" + data;
        } else if (typeof data === "object") {
          for (let key in data)
            ret += "&" + key + "=" + encodeURIComponent(data[key]);
        }
        ret += "&_time=" + Date.now();
      }
      url = `${url}?${ret}`;
      ajax.open(method, url);
      // send即可
      ajax.send();
    } else {
      ajax.open(method, url);
      // 需要设置请求报文
      ajax.setRequestHeader(
        "Content-type",
        "application/x-www-form-urlencoded"
      );
      if (data) {
        ajax.send(data);
      } else {
        ajax.send();
      }
    }
    // 注册事件
    ajax.onreadystatechange = () => {
      // 在事件中 获取数据 并修改界面显示
      if (ajax.readyState == 4 && ajax.status == 200) {
        const JsonData = ajax.responseText ? JSON.parse(ajax.responseText) : {};
        resolve(JsonData);
      }
    };
  });
};

type Point = [number, number];

export function isWithinNanjing(longitude: number, latitude: number): boolean {
  const polygon: any = nanjingJson?.features[0];
  // 要检查的经纬度点
  const pointToCheck = turf.point([longitude, latitude]); // 注意：经度在前，纬度在后

  // 判断点是否在多边形内
  const isInside = turf.booleanPointInPolygon(pointToCheck, polygon);
  return isInside;
}
